
(function($){

	var slide_next = function(me){
		var files = me.data("files"),
			n_files = me.data("n_files"),
			cur_file = me.data("cur_file");

		if ( n_files > 1 ){
			cur_file++;
			if ( cur_file >= n_files ){
				cur_file = 0;
			}
			me.data("cur_file", cur_file);
			return files[cur_file];
		}
		return false;
	},

	slideshowNext = function(e){
		var me=e.data,p,file,second_img;
	
		if ( me ){
			// Create the second image holder (the fading one)
			second_img = me.data("second_img");
			if ( !second_img ){
				second_img = me.clone(true);
				second_img.css("display", "none");
				second_img.css("position", "absolute");
				$(document.body).append( second_img );
				me.data("second_img", second_img);
			}
	
			// Set position and size for the second image holder...
			p = me.offset();
			second_img.css("left", p.left+"px")
					.css("top", p.top+"px")
					.width(me.width())
					.height(me.height());

			if ( (file = slide_next(me)) ) {
				second_img.attr("src", file);
				second_img.fadeIn( me.data("speed"), function(){
												me.attr("src", file);
												second_img.css("display", "none");
											});
			}
		}
	};

$.fn.SlideShow = function(delay,speed,atom_id){
	this.each(function() {
		var $this = $(this);
		$this.JsonRequest( {id:"SlideshowList",
						data:{'atom_id':atom_id},
						cb:function(d,e){
								var files = {},n=0;
								$.each( d.images, function(i,v){
												files[n++] = v;
											});
								$this.data("files",files);
								$this.data("n_files", n);
								$this.data("cur_file", 0);
							}});

		$this.data("speed", speed);
		$this.bind("slide_next", $this, slideshowNext);
		setInterval( "$('#"+$this.attr("id")+"').trigger('slide_next')", delay );
	});
};

}(jQuery));
